﻿using DevExpress.Data.Filtering;
using DevExpress.Data.Filtering.Helpers;

namespace EasyXaf.DynamicForm.Blazor;

public class CriteriaConverterProcessor : IClientCriteriaVisitor
{
    public Dictionary<string, string> NamedParameters = [];

    public void Visit(AggregateOperand theOperand)
    {
    }

    public void Visit(OperandProperty theOperand)
    {
    }

    public void Visit(JoinOperand theOperand)
    {
    }

    public void Visit(BetweenOperator theOperator)
    {
    }

    public void Visit(BinaryOperator theOperator)
    {
        if (!theOperator.LeftOperand.ReferenceEqualsNull())
        {
            theOperator.LeftOperand.Accept(this);
        }
        if (!theOperator.RightOperand.ReferenceEqualsNull())
        {
            theOperator.RightOperand.Accept(this);
        }
    }

    public void Visit(UnaryOperator theOperator)
    {
    }

    public void Visit(InOperator theOperator)
    {
    }

    public void Visit(GroupOperator theOperator)
    {
    }

    public void Visit(OperandValue theOperand)
    {
        var value = theOperand.Value?.ToString();
        if (value.StartsWith("@this.", StringComparison.OrdinalIgnoreCase))
        {
            var parameterName = value["@this.".Length..];
            if (IsValidParameterName(parameterName))
            {
                var key = Guid.NewGuid().ToString();
                NamedParameters.Add(key, parameterName);
                theOperand.Value = key;
            }
        }
    }

    public void Visit(FunctionOperator theOperator)
    {
    }

    private static bool IsValidParameterName(string parameterName)
    {
        if (CriteriaOperator.TryParse("?" + parameterName) is OperandParameter operandParameter)
        {
            return operandParameter.ParameterName == parameterName;
        }
        return false;
    }
}
